package cn.edu.zzuli.jucUtils;

import java.util.concurrent.Semaphore;

/**
 * @Date: 2021/3/8 19:52
 * @Author: 绯色下午茶
 * @Description:
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        /**
         * 三个车位
         */
        Semaphore semaphore = new Semaphore(1);
        for (int i = 0; i < 8; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire();//车位减一
                    System.out.println(Thread.currentThread().getName()+"抢到了车位");

                    Thread.sleep(4000);
                    System.out.println(Thread.currentThread().getName()+"离开了车位");
                } catch (InterruptedException e) {

                }finally {
                    semaphore.release();//释放车位
                }
            }, String.valueOf(i)).start();
        }
    }
}
